package handler

import (
	"encoding/json"
	"net/http"
	"github.com/zhulizhe/golang-shortlink/internal/service"
)

type Handler struct {
	Service *service.LinkService
}

func NewHandler(s *service.LinkService) *Handler {
	return &Handler{Service: s}
}

// 创建短链
func (h *Handler) CreateShortLink(w http.ResponseWriter, r *http.Request) {
	type reqBody struct {
		URL string `json:"url"`
	}
	var req reqBody
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.URL == "" {
		http.Error(w, "invalid request", http.StatusBadRequest)
		return
	}
	link := h.Service.CreateShortLink(req.URL)
	resp := map[string]string{
		"short_url": "/" + link.ShortKey,
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(resp)
}

// 短链重定向
func (h *Handler) Redirect(w http.ResponseWriter, r *http.Request) {
	shortKey := r.URL.Path[1:]
	if shortKey == "" {
		http.NotFound(w, r)
		return
	}
	url, ok := h.Service.GetOriginalURL(shortKey)
	if !ok {
		http.NotFound(w, r)
		return
	}
	http.Redirect(w, r, url, http.StatusFound)
}

// 查询短链统计
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
	shortKey := r.URL.Query().Get("key")
	if shortKey == "" {
		http.Error(w, "missing key", http.StatusBadRequest)
		return
	}
	link, ok := h.Service.GetStats(shortKey)
	if !ok {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(link)
}
